package team.fivez.defaultmanage.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import team.fivez.defaultmanage.dao.ApplicantDao;
import team.fivez.defaultmanage.domain.Applicant;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
public class ApplicantService {


    private final ApplicantDao applicantDao;

    @Autowired
    public ApplicantService(ApplicantDao applicantDao) {
        this.applicantDao = applicantDao;
    }


    //申请人登录，0成功，1失败
    public int login(Applicant applicant) throws NoSuchAlgorithmException {
        System.out.println(applicant);
        //查找该用户是否存在
        Integer count = applicantDao.getCountByApplicantAccount(applicant.getApplicantAccount());
        if(count != 1){
            return 1;//不存在该用户
        }
        Applicant applicantFromDB = applicantDao.getApplicantByApplicantAccount(applicant.getApplicantAccount());
        //将密码加密判断
        MessageDigest md = MessageDigest.getInstance("SHA");
        byte[] digest = md.digest(applicant.getApplicantPassword().getBytes());
        BigInteger bigInteger = new BigInteger(1, digest);
        String password_new = bigInteger.toString(16);

        if (password_new.equals(applicantFromDB.getApplicantPassword())){
            return 0;
        }
        else return 1;

    }

    //申请人注册，0成功，1失败
    public int register(Applicant applicant) throws NoSuchAlgorithmException {
        //查找用户是否存在
        Integer count = applicantDao.getCountByApplicantAccount(applicant.getApplicantAccount());
        if(count==1){
            return 1;//用户已经存在
        }
        //将密码加密
        MessageDigest md = MessageDigest.getInstance("SHA");
        byte[] digest = md.digest(applicant.getApplicantPassword().getBytes());
        BigInteger bigInteger = new BigInteger(1, digest);
        String password_new = bigInteger.toString(16);

        //设置加密密码
        applicant.setApplicantPassword(password_new);

        int i = applicantDao.insertApplicant(applicant);

        if (i==1){
            return 0;
        }
        else return 1;

    }



}
